package com.avengers.common.kit;
// 版权所有 © 艾科瑞特科技
// 艾科瑞特（iCREDIT）-让企业业绩长青
// 预知更多业绩长青，请与我们联系
// 联系电话：0532-88984128
// 联系邮箱：market@itruth.xin

import com.avengers.common.kit.bean.VerifyResult;
import com.avengers.core.bean.enums.Charset;
import com.avengers.core.bean.enums.HttpEnum;
import com.avengers.core.kit.JsonKit;
import com.avengers.core.kit.StringKit;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * @author yu.wang
 * @since 2020-10-30 09:34
 **/
public class ImageCodeVerify {
    private static final Logger logger = LoggerFactory.getLogger(ImageCodeVerify.class);
    /**
     * API产品路径
     */
    private static final String REQUEST_URL = "https://codevirify.market.alicloudapi.com/icredit_ai_image/verify_code/v1";
    /**
     * 阿里云APPCODE
     */
    private static final String APP_CODE = "36dd9246114745218a8d3b5127ead049";

    /**
     * 识别图片验证码
     *
     * @param imgFilePath 图片路径
     * @return 验证码
     */
    public static String getCode(String imgFilePath) {
        CloseableHttpClient httpClient = null;
        String resultStr = "";
        try {
            httpClient = HttpClients.createDefault();
            List<NameValuePair> params = new ArrayList<>();
            // 装填参数
            //启用BASE64编码方式进行识别
            //内容数据类型是BASE64编码
            String imgBase64 = "";
            File file = new File(imgFilePath);
            byte[] content = new byte[(int) file.length()];
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(content);
            fileInputStream.close();
            imgBase64 = new String(encodeBase64(content));
            params.add(new BasicNameValuePair("IMAGE", imgBase64));
            params.add(new BasicNameValuePair("IMAGE_TYPE", "0"));

            // 创建一个HttpGet实例
            HttpPost httpPost = new HttpPost(REQUEST_URL);
            httpPost.addHeader(HttpEnum.AUTHORIZATION.value, "APPCODE " + APP_CODE);
            httpPost.addHeader(HttpEnum.CONTENT_TYPE.value, HttpEnum.APPLICATION_FORM_CHARSET.value);

            // 设置请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.UTF8.value));

            // 发送GET请求
            HttpResponse execute = httpClient.execute(httpPost);

            // 获取结果
            HttpEntity entity = execute.getEntity();
            resultStr = EntityUtils.toString(entity, Charset.UTF8.value);
            if (StringKit.isBlank(resultStr)) {
                return null;
            }
            VerifyResult result = JsonKit.fromJson(resultStr, VerifyResult.class);
            return result.getEntity().getCode();
        } catch (Exception e) {
            logger.error("check file path_{} result: {} error: {}", imgFilePath, resultStr, e.getMessage(), e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
